package cn.xlbweb.sso.listener;

import cn.xlbweb.sso.entity.ClientDTO;
import cn.xlbweb.sso.service.IClientService;
import cn.xlbweb.sso.service.IServerService;
import cn.xlbweb.sso.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;

/**
 * @author: bobi
 * @date: 2019-03-24 18:50
 * @description:
 */
@WebListener
public class SsoSessionListener implements HttpSessionListener {

    @Autowired
    private IServerService iServerService;

    @Autowired
    private IClientService iClientService;

    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        String token = (String) session.getAttribute("token");
        // 获取当前浏览器所有的登陆子系统
        List<ClientDTO> clientList = iClientService.findByToken(token);
        for (ClientDTO client : clientList) {
            HttpUtil.sendHttpRequest(client.getClientUrl() + "/logout", client.getJsessionId());
        }
        // 删除token
        iServerService.deleteByToken(token);
        // 删除client
        iClientService.deleteByToken(token);
    }
}
